<?php
/**
 *
 * User: cfn
 * Date: 2020/10/14
 * Email: <cfn@leapy.cn>
 */

namespace app\common\util;


use GuzzleHttp\Client;
use GuzzleHttp\Exception\GuzzleException;
use think\Log;

/**
 * Class Http
 * @package alisha\toolkit
 */
class Http
{
    //证书路径，为false，不使用证书
    private static $verify = false;

    /**
     * @param $url
     * @param array $data
     * @param array $header
     * @return mixed|null
     * get请求
     */
    public static function get($url, $data = [], $header = [])
    {
        try {
            $client = new Client(['verify' => self::$verify]);
            $response = $client->request('GET', $url, [
                'headers' => $header,
                //get传参，和post有区别
                'query' => $data
            ])->getBody()->getContents();
            return json_decode($response, true);
        } catch (GuzzleException $e) {
            Log::error($e->getMessage());
            return null;
        }
    }
    public static function json($url, $data = [], $header = [])
    {
        try {
            $client = new Client(['verify' => self::$verify]);
            $response = $client->request('POST', $url, [
                'headers' => $header,
                'json' => $data
            ])->getBody()->getContents();
            return json_decode($response, true);
        } catch (GuzzleException $e) {
            Log::error($e->getMessage());
            return null;
        }
    }
    public static function post($url, $data = [], $header = [])
    {
        try {
            $client = new Client(['verify' => self::$verify]);
            $response = $client->request('POST', $url, [
                'headers' => $header,
                //post请求传参
                'form_params' => $data
            ])->getBody()->getContents();
            return json_decode($response, true);
        } catch (GuzzleException $e) {
            Log::error($e->getMessage());
            return null;
        }
    }
    public static function jsonPost($url, $data = [], $header = [])
    {
        try {
            $client = new Client(['verify' => self::$verify]);
            $response = $client->request('POST', $url, [
                'headers' => $header,
                'json' => $data
            ])->getBody()->getContents();
            return $response;
        } catch (GuzzleException $e) {
            Log::error($e->getMessage());
            return null;
        }
    }
}
